<template>
  <div class="dashboard-container">
    <!-- 统计卡片 -->
    <el-row :gutter="20" class="stats-row">
      <el-col :xs="24" :sm="12" :md="6">
        <el-card class="stats-card" shadow="hover">
          <div class="stats-content">
            <div class="stats-icon">
              <el-icon><User /></el-icon>
            </div>
            <div class="stats-info">
              <div class="stats-value">{{ stats.totalUsers || 0 }}</div>
              <div class="stats-label">总用户数</div>
            </div>
          </div>
        </el-card>
      </el-col>
      <el-col :xs="24" :sm="12" :md="6">
        <el-card class="stats-card" shadow="hover">
          <div class="stats-content">
            <div class="stats-icon">
              <el-icon><Document /></el-icon>
            </div>
            <div class="stats-info">
              <div class="stats-value">{{ stats.totalFiles || 0 }}</div>
              <div class="stats-label">总文件数</div>
            </div>
          </div>
        </el-card>
      </el-col>
      <el-col :xs="24" :sm="12" :md="6">
        <el-card class="stats-card" shadow="hover">
          <div class="stats-content">
            <div class="stats-icon">
              <el-icon><Folder /></el-icon>
            </div>
            <div class="stats-info">
              <div class="stats-value">{{ formatStorage(stats.totalStorage) }}</div>
              <div class="stats-label">总存储空间</div>
            </div>
          </div>
        </el-card>
      </el-col>
      <el-col :xs="24" :sm="12" :md="6">
        <el-card class="stats-card" shadow="hover">
          <div class="stats-content">
            <div class="stats-icon">
              <el-icon><UserFilled /></el-icon>
            </div>
            <div class="stats-info">
              <div class="stats-value">{{ stats.newUsersToday || 0 }}</div>
              <div class="stats-label">今日新增用户</div>
            </div>
          </div>
        </el-card>
      </el-col>
    </el-row>

    <!-- 图表区域 -->
    <el-row :gutter="20" class="chart-row">
      <el-col :xs="24" :lg="12">
        <el-card class="chart-card" shadow="hover">
          <template #header>
            <div class="card-header">
              <span>用户增长趋势</span>
            </div>
          </template>
          <div class="chart-container" ref="userGrowthChart"></div>
        </el-card>
      </el-col>
      <el-col :xs="24" :lg="12">
        <el-card class="chart-card" shadow="hover">
          <template #header>
            <div class="card-header">
              <span>存储空间使用情况</span>
            </div>
          </template>
          <div class="chart-container" ref="storageChart"></div>
        </el-card>
      </el-col>
    </el-row>

    <!-- 最近活动 -->
    <el-card class="activity-card" shadow="hover">
      <template #header>
        <div class="card-header">
          <span>最近活动</span>
        </div>
      </template>
      <el-timeline>
        <el-timeline-item
          v-for="(activity, index) in recentActivities"
          :key="index"
          :timestamp="activity.timestamp"
          :type="activity.type"
        >
          {{ activity.content }}
        </el-timeline-item>
      </el-timeline>
    </el-card>
  </div>
</template>

<script setup>
import { ref, onMounted, onUnmounted, getCurrentInstance, nextTick } from 'vue'
import { User, Document, Folder, UserFilled } from '@element-plus/icons-vue'
import * as echarts from 'echarts'
import { getDashboardOverview, getStorageTrend, getRecentActivity, getFileTypeDistribution, getUserTrend } from '@/api/admin'

const { proxy } = getCurrentInstance()

// 统计数据
const stats = ref({
  totalUsers: 0,
  totalFiles: 0,
  totalStorage: 0,
  newUsersToday: 0
})

// 图表实例
let userGrowthChartInstance = null
let storageChartInstance = null

// 最近活动
const recentActivities = ref([])

// 加载概览数据
const loadOverviewData = async () => {
  try {
    const res = await getDashboardOverview()
    if (res.code === 200) {
      stats.value = {
        totalUsers: res.data.totalUsers || 0,
        totalFiles: res.data.totalFiles || 0,
        totalStorage: res.data.totalStorage || 0,
        newUsersToday: res.data.newUsersToday || 0
      }
    }
  } catch (error) {
    console.error('加载概览数据失败:', error)
  }
}

// 加载用户增长趋势
const loadUserTrend = async () => {
  try {
    const days = 7 // 获取最近7天的数据
    const res = await getUserTrend(days)
    if (res.code === 200 && userGrowthChartInstance) {
      console.log('User trend data:', res.data); // 添加调试日志
      
      const dates = res.data.map(item => item.date)
      const counts = res.data.map(item => Number(item.count) || 0)
      
      const option = {
        tooltip: {
          trigger: 'axis',
          formatter: function(params) {
            return `${params[0].name}<br/>
                   新增用户: ${params[0].value}`;
          }
        },
        grid: {
          left: '3%',
          right: '4%',
          bottom: '3%',
          containLabel: true
        },
        xAxis: {
          type: 'category',
          boundaryGap: false,
          data: dates,
          axisLabel: {
            formatter: (value) => {
              return value.substring(5) // 只显示月-日
            }
          }
        },
        yAxis: {
          type: 'value',
          minInterval: 1 // 确保y轴刻度为整数
        },
        series: [
          {
            name: '新增用户',
            type: 'line',
            smooth: true,
            data: counts,
            areaStyle: {
              opacity: 0.3,
              color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
                { offset: 0, color: '#409EFF' },
                { offset: 1, color: 'rgba(64,158,255,0.1)' }
              ])
            },
            lineStyle: {
              width: 2,
              color: '#409EFF'
            },
            itemStyle: {
              color: '#409EFF'
            }
          }
        ]
      }
      
      userGrowthChartInstance.setOption(option)
    }
  } catch (error) {
    console.error('加载用户趋势数据失败:', error)
  }
}

// 加载存储空间使用趋势
const loadStorageTrend = async () => {
  try {
    const days = 7 // 获取最近7天的数据
    const res = await getStorageTrend(days)
    if (res.code === 200 && storageChartInstance) {
      console.log('Storage trend data:', res.data);
      
      // 确保数据按日期排序
      const sortedData = [...res.data].sort((a, b) => new Date(a.date) - new Date(b.date));
      
      const dates = sortedData.map(item => item.date)
      const storage = sortedData.map(item => {
        const value = parseFloat(item.storage);
        return value || 0;
      })
      
      const option = {
        tooltip: {
          trigger: 'axis',
          formatter: function(params) {
            const dataIndex = params[0].dataIndex;
            const data = sortedData[dataIndex];
            return `日期：${data.date}<br/>
                   新增存储：${formatStorage(data.storage)}`;
          }
        },
        grid: {
          left: '3%',
          right: '4%',
          bottom: '3%',
          containLabel: true
        },
        xAxis: {
          type: 'category',
          boundaryGap: false,
          data: dates,
          axisLabel: {
            formatter: (value) => {
              return value.substring(5) // 只显示月-日
            }
          }
        },
        yAxis: {
          type: 'value',
          name: '存储空间',
          axisLabel: {
            formatter: (value) => formatStorage(value)
          }
        },
        series: [
          {
            name: '新增存储空间',
            type: 'line',
            smooth: true,
            data: storage,
            areaStyle: {
              opacity: 0.3,
              color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
                { offset: 0, color: '#409EFF' },
                { offset: 1, color: 'rgba(64,158,255,0.1)' }
              ])
            },
            lineStyle: {
              width: 2,
              color: '#409EFF'
            },
            itemStyle: {
              color: '#409EFF'
            }
          }
        ]
      }
      
      storageChartInstance.setOption(option)
    }
  } catch (error) {
    console.error('加载存储趋势数据失败:', error)
  }
}

// 加载最近活动
const loadRecentActivity = async () => {
  try {
    const res = await getRecentActivity()
    if (res.code === 200) {
      recentActivities.value = res.data.map(activity => ({
        content: `用户${activity.nickName}${activity.folderType === 1 ? '上传了文件' : '创建了文件夹'}"${activity.fileName}"`,
        timestamp: activity.lastUpdateTime,
        type: activity.folderType === 1 ? 'primary' : 'success'
      }))
    }
  } catch (error) {
    console.error('加载最近活动失败:', error)
  }
}

// 格式化存储空间
const formatStorage = (bytes) => {
  if (!bytes) return '0 B'
  const units = ['B', 'KB', 'MB', 'GB', 'TB']
  let index = 0
  let size = bytes
  while (size >= 1024 && index < units.length - 1) {
    size /= 1024
    index++
  }
  return `${size.toFixed(2)} ${units[index]}`
}

// 初始化图表
const initCharts = () => {
  initUserGrowthChart()
  initStorageChart()
}

// 初始化用户增长趋势图表
const initUserGrowthChart = () => {
  const chartDom = proxy.$refs.userGrowthChart
  if (!chartDom) return
  
  nextTick(() => {
    userGrowthChartInstance = echarts.init(chartDom)
    loadUserTrend()
  })
}

// 初始化存储空间使用图表
const initStorageChart = () => {
  const chartDom = proxy.$refs.storageChart
  if (!chartDom) return
  
  nextTick(() => {
    storageChartInstance = echarts.init(chartDom)
    loadStorageTrend()
  })
}

// 监听窗口大小变化
const handleResize = () => {
  userGrowthChartInstance?.resize()
  storageChartInstance?.resize()
}

onMounted(() => {
  loadOverviewData()
  initCharts()
  loadRecentActivity()
  window.addEventListener('resize', handleResize)
})

onUnmounted(() => {
  window.removeEventListener('resize', handleResize)
  userGrowthChartInstance?.dispose()
  storageChartInstance?.dispose()
})
</script>

<style lang="scss" scoped>
.dashboard-container {
  .stats-row {
    margin-bottom: 20px;
    
    .stats-card {
      height: 120px;
      border: none;
      background: linear-gradient(to right, #fff, #fafafa);
      transition: all 0.3s;
      
      &:hover {
        transform: translateY(-4px);
        box-shadow: 0 4px 12px rgba(0,0,0,0.1);
        
        .stats-icon {
          transform: scale(1.1);
        }
      }
      
      .stats-content {
        height: 100%;
        display: flex;
        align-items: center;
        padding: 20px;
        
        .stats-icon {
          width: 60px;
          height: 60px;
          border-radius: 12px;
          display: flex;
          align-items: center;
          justify-content: center;
          margin-right: 20px;
          transition: all 0.3s;
          
          .el-icon {
            font-size: 30px;
            color: #fff;
          }
          
          &:nth-child(1) {
            background: linear-gradient(120deg, #bd34fe 30%, #47caff);
          }
        }
        
        .stats-info {
          flex: 1;
          
          .stats-value {
            font-size: 24px;
            font-weight: bold;
            color: #303133;
            margin-bottom: 4px;
          }
          
          .stats-label {
            font-size: 14px;
            color: #909399;
          }
        }
      }
    }
  }
  
  .chart-row {
    margin-bottom: 20px;
    
    .chart-card {
      border: none;
      background: linear-gradient(to right, #fff, #fafafa);
      transition: all 0.3s;
      
      &:hover {
        transform: translateY(-4px);
        box-shadow: 0 4px 12px rgba(0,0,0,0.1);
      }
      
      .card-header {
        padding: 16px 20px;
        border-bottom: 1px solid #f0f0f0;
        
        span {
          font-size: 16px;
          font-weight: bold;
          background: linear-gradient(120deg, #bd34fe 30%, #47caff);
          -webkit-background-clip: text;
          -webkit-text-fill-color: transparent;
        }
      }
      
      .chart-container {
        height: 300px;
        padding: 20px;
      }
    }
  }
  
  .activity-card {
    border: none;
    background: linear-gradient(to right, #fff, #fafafa);
    transition: all 0.3s;
    
    &:hover {
      transform: translateY(-4px);
      box-shadow: 0 4px 12px rgba(0,0,0,0.1);
    }
    
    .card-header {
      padding: 16px 20px;
      border-bottom: 1px solid #f0f0f0;
      
      span {
        font-size: 16px;
        font-weight: bold;
        background: linear-gradient(120deg, #bd34fe 30%, #47caff);
        -webkit-background-clip: text;
        -webkit-text-fill-color: transparent;
      }
    }
    
    :deep(.el-timeline) {
      padding: 20px;
      
      .el-timeline-item {
        .el-timeline-item__node {
          &.el-timeline-item__node--primary {
            background-color: #409EFF;
          }
          
          &.el-timeline-item__node--success {
            background-color: #67C23A;
          }
          
          &.el-timeline-item__node--warning {
            background-color: #E6A23C;
          }
        }
        
        .el-timeline-item__content {
          color: #606266;
        }
        
        .el-timeline-item__timestamp {
          color: #909399;
        }
      }
    }
  }
}

// 响应式布局
@media screen and (max-width: 768px) {
  .dashboard-container {
    .stats-row {
      .el-col {
        margin-bottom: 20px;
        
        &:last-child {
          margin-bottom: 0;
        }
      }
    }
    
    .chart-row {
      .el-col {
        margin-bottom: 20px;
        
        &:last-child {
          margin-bottom: 0;
        }
      }
    }
  }
}
</style> 